<?php

namespace app\index\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Attachment;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use addons\epay\library;

/**
 * 会员中心
 */
class User extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third', 'yinsi', 'xieyi', 'nkyinsi', 'nkxieyi'];
    protected $noNeedRight = ['*'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录退出的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        $this->model = new \app\admin\model\yexam\Subject;
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->view->assign('title', __('User center'));
        return $this->view->fetch();
    }

    /**
     * 注册会员
     */
    public function register()
    {
        $url = $this->request->request('url', '', 'trim');
        $source = $this->request->request('source', '', 'trim');
        $ename = $this->request->request('ename', '', 'trim');
        $cn_name = '';
        if($ename){
            $row = $this->model->get(['en_name'=>$ename]);
            if($row) $cn_name = $row['short_name'];
        }
        $client = cmf_is_mobile() ? 'm' : 'pc';
        if ($this->auth->id) {
//            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('index/index'));
            $ename = $ename ? : $this->auth->class_name;
            header('location:'. url('Common/head',array('enname'=>$ename,'client'=>$client)));
            exit;
        }
        if ($this->request->isPost()) {
            // $username = $this->request->post('username');
            $password = $this->request->post('password');
            // $email = $this->request->post('email');
            $email = '';
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                // 'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                // 'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                '__token__' => 'require|token',
            ];

            $msg = [
                // 'username.require' => 'Username can not be empty',
                // 'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                // 'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                // 'username'  => $username,
                'password'  => $password,
                // 'email'     => $email,
                'mobile'    => $mobile,
                '__token__' => $token,
            ];
            //验证码
            $captchaResult = true;
            $captchaType = config("fastadmin.user_register_captcha");
            if ($captchaType) {
                if ($captchaType == 'mobile') {
                    $captchaResult = Sms::check($mobile, $captcha, 'register');
//                } elseif ($captchaType == 'email') {
//                    $captchaResult = Ems::check($email, $captcha, 'register');
                } elseif ($captchaType == 'wechat') {
                    $captchaResult = WechatCaptcha::check($captcha, 'register');
                } elseif ($captchaType == 'text') {
                    $captchaResult = \think\Validate::is($captcha, 'captcha');
                }
            }
            if (!$captchaResult) {
                $this->error(__('Captcha is incorrect'));
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            $username = $mobile;
            if($this->auth->isUser($mobile)){
                if ($this->auth->login($mobile, $password)) {

                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }else{
                // Set default username, email...

                $extend['entry_platform'] = $client;
                $extend['url_source'] = $source;
                $extend['class_name'] = $ename;
                $extend['class_title'] = $cn_name;
                if ($this->auth->register($username, $password, $email, $mobile,$extend)) {

                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }

            // ksbao 同步注册
            $website = cmf_get_website_value();
            $ksbao_data = [
                'userName' => $username,
                'password' => $password,
                'client'   => $client,
                'partnercode' => $website['partnercode'],
            ];
            $ksbao_reg_url = cmf_get_ksbao_value('nregist');
            $json = cmf_send_post($ksbao_reg_url, $ksbao_data, $website['client_ip']);
            $return_arr = json_decode($json, true);
            if ($return_arr['status'] != 200) {
                $this->error('同步失败,请联系管理员');
            } else {
                $appEName =  $ename ? :($return_arr['data']['appEName'] ?? '');
//                $appVn =  $data['vn'] ?? ($return_arr['data']['appVn'] ?? 0);
                \session('guid', $return_arr['data']['guid']);
            }
            // /ksbao 同步注册

//                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
//            var_dump(url('Common/head',array('enname'=>$appEName,'client'=>$client)));exit;
            $this->success('注册/登录成功', url('Common/head',array('enname'=>$appEName,'client'=>$client)));
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('url', $url);
        $this->view->assign('ename', $ename);
        $this->view->assign('cn_name', $cn_name);
        $this->view->assign('source', $source);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url', '', 'trim');
        $source = $this->request->request('source', '', 'trim');
        $ename = $this->request->request('ename', '', 'trim');
        $cn_name = '';
        if($ename){
            $row = $this->model->get(['en_name'=>$ename]);
            if($row) $cn_name = $row['short_name'];
        }
        $client = cmf_is_mobile() ? 'm' : 'pc';
        if ($this->auth->id) {
//            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('index/index'));
            $ename = $ename ? : $this->auth->class_name;
            header('location:'. url('Common/head',array('enname'=>$ename,'client'=>$client)));
            exit;
        }
        if ($this->request->isPost()) {
            // $username = $this->request->post('username');
            $password = $this->request->post('password');
            // $email = $this->request->post('email');
            $email = '';
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                // 'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                // 'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                '__token__' => 'require|token',
            ];

            $msg = [
                // 'username.require' => 'Username can not be empty',
                // 'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                // 'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                // 'username'  => $username,
                'password'  => $password,
                // 'email'     => $email,
                'mobile'    => $mobile,
                '__token__' => $token,
            ];
            //验证码
            $captchaResult = true;
            $captchaType = config("fastadmin.user_register_captcha");
            if ($captchaType) {
                if ($captchaType == 'mobile') {
                    $captchaResult = Sms::check($mobile, $captcha, 'register');
//                } elseif ($captchaType == 'email') {
//                    $captchaResult = Ems::check($email, $captcha, 'register');
                } elseif ($captchaType == 'wechat') {
                    $captchaResult = WechatCaptcha::check($captcha, 'register');
                } elseif ($captchaType == 'text') {
                    $captchaResult = \think\Validate::is($captcha, 'captcha');
                }
            }
            if (!$captchaResult) {
                $this->error(__('Captcha is incorrect'));
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            $username = $mobile;
            if($this->auth->isUser($mobile)){
                if ($this->auth->login($mobile, $password)) {

                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }else{
                // Set default username, email...

                $extend['entry_platform'] = $client;
                $extend['url_source'] = $source;
                $extend['class_name'] = $ename;
                $extend['class_title'] = $cn_name;

                if ($this->auth->register($username, $password, $email, $mobile,$extend)) {

                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }

            // ksbao 同步注册
            $website = cmf_get_website_value();
            $ksbao_data = [
                'userName' => $username,
                'password' => $password,
                'client'   => $client,
                'partnercode' => $website['partnercode'],
            ];
            $ksbao_reg_url = cmf_get_ksbao_value('nregist');
            $json = cmf_send_post($ksbao_reg_url, $ksbao_data, $website['client_ip']);
            $return_arr = json_decode($json, true);
            if ($return_arr['status'] != 200) {
                $this->error('同步失败,请联系管理员');
            } else {
                $appEName =  $ename ? :($return_arr['data']['appEName'] ?? '');
//                $appVn =  $data['vn'] ?? ($return_arr['data']['appVn'] ?? 0);
                \session('guid', $return_arr['data']['guid']);
            }
            // /ksbao 同步注册

//                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
//            var_dump(url('Common/head',array('enname'=>$appEName,'client'=>$client)));exit;
            $this->success('注册/登录成功', url('Common/head',array('enname'=>$appEName,'client'=>$client)));
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('url', $url);
        $this->view->assign('ename', $ename);
        $this->view->assign('cn_name', $cn_name);
        $this->view->assign('source', $source);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch('register');
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        //退出本站
        $this->auth->logout();
        $this->success(__('Logout successful'), url('/user/login'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 订单管理
     */
    public function order()
    {
		$order = new \app\admin\model\Xorder;
		$xorders = $order->where(['user_id'=>$this->auth->id])->where('deletetime is null')->order('id desc')->paginate(20);
		
		$result = array("total" => $xorders->total(), "rows" => $xorders->items());
		// var_dump($result);
        $this->view->assign('result', $result);
        $this->view->assign('title', __('Order'));
        return $this->view->fetch();
    }
	
	//支付
	public function pay(){
		$xid = $this->request->param('xid');
		if(!$xid) $this->error('订单错误');
		$order = new \app\admin\model\Xorder;
		$xorder = $order->get(['id'=>$xid,'user_id'=>$this->auth->id]);
		if(!$xorder) $this->error('订单错误');
		$payment_content = json_decode($xorder['payment_content'],true);
		$params = [
                'amount'    => $xorder['actual_amount']/100,
                'orderid'   => $xorder['order_no'],
                'type'      => $xorder['paytype'],
                'title'     => $xorder['title'],
                'notifyurl' => $payment_content['notifyurl'],
                'returnurl' => $payment_content['returnurl'],
                'method'    => 'web',
                'openid'    => '',
            ];
		Session::set("wechatorderdata", $params);
		$url = addon_url('epay/api/wechat', [], true, true);
		return \addons\epay\library\RedirectResponse::create($url);
		
	}
	    /**
     * 激活码
     */
    public function jihuoma()
    {
        $this->view->assign('title', __('Jihuoma'));
        return $this->view->fetch();
    }
	    /**
     * 做题
     */
    public function zuoti()
    {
        $this->view->assign('title', __('Zuoti'));
        return $this->view->fetch();
    }
		    /**
     * 下载
     */
    public function xiazai()
    {
        $this->view->assign('title', __('Xiazai'));
        return $this->view->fetch();
    }
	public function xieyi()
    {
        $this->view->assign('title', __('用户协议'));
        return $this->view->fetch();
    }
	public function yinsi()
    {
        $this->view->assign('title', __('隐私协议'));
        return $this->view->fetch();
    }
	public function nkxieyi()
    {
        $this->view->assign('title', __('牛课用户协议'));
        return $this->view->fetch();
    }
	public function nkyinsi()
    {
        $this->view->assign('title', __('牛课隐私协议'));
        return $this->view->fetch();
    }
			    /**
     * 下载
     */
    public function xiangqing()
    {
		$out_trade_no = $this->request->param('out_trade_no');
		$order = new \app\admin\model\Xorder;
		$xorder = $order->get(['order_no'=>$out_trade_no]);
		if(!$xorder) $this->error('订单错误');
		// var_dump($xorder->toArray());
		$this->view->assign('xorder',$xorder);
        $this->view->assign('title', __('Xiangqinbg'));
        return $this->view->fetch();
    }
    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
                'renewpassword.confirm' => __('Password and confirm password don\'t match')
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    public function attachment()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $mimetypeQuery = [];
            $where = [];
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            if (isset($filterArr['mimetype']) && preg_match("/[]\,|\*]/", $filterArr['mimetype'])) {
                $this->request->get(['filter' => json_encode(array_diff_key($filterArr, ['mimetype' => '']))]);
                $mimetypeQuery = function ($query) use ($filterArr) {
                    $mimetypeArr = explode(',', $filterArr['mimetype']);
                    foreach ($mimetypeArr as $index => $item) {
                        if (stripos($item, "/*") !== false) {
                            $query->whereOr('mimetype', 'like', str_replace("/*", "/", $item) . '%');
                        } else {
                            $query->whereOr('mimetype', 'like', '%' . $item . '%');
                        }
                    }
                };
            } elseif (isset($filterArr['mimetype'])) {
                $where['mimetype'] = ['like', '%' . $filterArr['mimetype'] . '%'];
            }

            if (isset($filterArr['filename'])) {
                $where['filename'] = ['like', '%' . $filterArr['filename'] . '%'];
            }

            if (isset($filterArr['createtime'])) {
                $timeArr = explode(' - ', $filterArr['createtime']);
                $where['createtime'] = ['between', [strtotime($timeArr[0]), strtotime($timeArr[1])]];
            }

            $model = new Attachment();
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);
            $total = $model
                ->where($where)
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->count();

            $list = $model
                ->where($where)
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->limit($offset, $limit)
                ->select();
            $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
            foreach ($list as $k => &$v) {
                $v['fullurl'] = ($v['storage'] == 'local' ? $cdnurl : $this->view->config['upload']['cdnurl']) . $v['url'];
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->view->assign("mimetypeList", \app\common\model\Attachment::getMimetypeList());
        return $this->view->fetch();
    }
}
